package com.fg.pro.model.utils;

import com.fg.pro.model.exception.CustomException;
import lombok.Data;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Component;

import static com.fg.pro.model.enums.AppHttpCodeEnum.POI_EXCEL_ERROR;

@Component
public class PoiUtils {

    public Double getDoubleByCellIndex(Row row ,int index){
        if(row==null){
            return 0d;
        }
        Cell cell = row.getCell(index);
        if(cell ==null){
            return 0d;
        }
        if(cell.getCellType()== CellType.NUMERIC){
            return cell.getNumericCellValue();
        }
        if(cell.getCellType()==CellType.STRING){
            return Double.valueOf(cell.getStringCellValue());
        }
        if(cell.getCellType()==CellType.ERROR || cell.getCellType() == CellType._NONE|| cell.getCellType() == CellType.BLANK){
            return 0d;
        }
        throw new CustomException(POI_EXCEL_ERROR);
    }

    public String getStringByCellIndex(Row row ,int index){
        if(row==null){
            return "";
        }
        Cell cell = row.getCell(index);
        if(cell ==null){
            return "";
        }
        if(cell.getCellType()== CellType.NUMERIC){
            return String.valueOf(cell.getNumericCellValue());
        }
        if(cell.getCellType()==CellType.STRING){
            return cell.getStringCellValue().trim();
        }
        if(cell.getCellType()==CellType.ERROR || cell.getCellType() == CellType._NONE|| cell.getCellType() == CellType.BLANK){
            return "";
        }
        throw new CustomException(POI_EXCEL_ERROR);
    }

}
